<template>
  <div
    style="
      height: 50px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      text-align: center;
      line-height: 50px;
    "
  >
    人脸绑定
  </div>
  <div style="text-align: center; line-height: 50px; margin-top: 30px">
    <!-- 主页面容器，红色背景，居中显示 -->
    <div ref="wrapper" class="w-full h-full bg-red flex flex-col items-center">
      <!-- 视频元素容器 -->
      <video ref="videoEl" style="border-radius: 50%" />
    </div>
    <el-button
      @click="shoot()"
      style="
        background-color: blue;
        color: white;
        width: 250px;
        height: 40px;
        margin-top: 30px;
      "
      >进行绑定</el-button
    >
    <div
      style="
        width: 100vw;
        height: 8vh;
        bottom: 0px;
        position: absolute;
        background-color: rgb(245, 245, 245);
        z-index: 9999999;
      "
    ></div>
  </div>
</template>
  
  <script setup lang="ts">
import axios from "axios";
import { ElMessage } from "element-plus";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { bindface } from "./services/faceLogin";
let router = useRouter();

//使用 ref 对象来获取 DOM 元素
const wrapper = ref();
const videoEl = ref();

// 检查摄像头并设置视频流
async function checkCamera() {
  // 获取媒体设备信息
  const navigator = window.navigator.mediaDevices;
  //判断用户是否拥有摄像头
  const devices = await navigator.enumerateDevices();

  // 如果存在媒体设备，获取摄像头视频流
  if (devices) {
    // 请求用户媒体设备（摄像头）
    const stream = await navigator.getUserMedia({
      audio: false,
      video: {
        width: 300, // 设置视频宽度
        height: 300, // 设置视频高度
        facingMode: "user", // 使用前置摄像头
      },
    });

    // 如果视频元素存在，将视频流绑定到视频元素上并开始播放
    if (videoEl.value) {
      videoEl.value.srcObject = stream;
      videoEl.value.play();
    }
  }
}

// 拍摄函数，截取摄像头当前帧并显示在页面上
function shoot() {
  // 检查视频元素和页面容器是否存在
  if (!videoEl.value || !wrapper.value) return;

  // 创建一个画布元素，设置画布尺寸为视频流的尺寸
  const canvas = document.createElement("canvas");
  canvas.width = videoEl.value.videoWidth / 2;
  canvas.height = videoEl.value.videoHeight / 2;

  // 获取画布上下文对象
  const ctx = canvas.getContext("2d");

  // 绘制当前视频帧到画布上
  ctx?.drawImage(videoEl.value, 0, 0, canvas.width, canvas.height);

  // 将画布内容转为 Base64 数据
  const imageDataUrl = canvas.toDataURL("image/png", 0.1);
  submitImages(imageDataUrl);
}

async function submitImages(img: string) {
  let user = JSON.parse(localStorage.getItem("user")) || null;
  console.log(user, 1111111111111111);
  const res: any = await bindface({ b64: img, item: user });
  if (res.code === 200) {
    ElMessage({
      message: res.msg,
      type: "success",
    });
    router.push("/login");
  } else {
    ElMessage({
      message: res.msg,
      type: "error",
    });
  }
}

onMounted(() => {
  checkCamera();
});
</script>
  
  <style></style>